package com.zac.pomodoro

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.annotation.DrawableRes
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import com.zac.pomodoro.TaskListActivity.Companion.KEY_JOBS
import com.zac.pomodoro.bean.Task
import com.zac.pomodoro.ui.theme.PausableCountDownTimer
import com.zac.pomodoro.ui.theme.PomodoroTheme
import com.zac.pomodoro.viewmodel.ViewModel

class MainActivity : ComponentActivity() {

    var timeSecond = 5
    private lateinit var timer: PausableCountDownTimer
    private val viewModel: ViewModel by viewModels()

    companion object {
        const val HOME = "home"
        const val FIND = "find"
        const val ME = "me"
    }

    private val launcher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {

        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        viewModel.taskList.addAll(loadJobs())
        timeSecond = if (viewModel.taskList.size > 0) {
            (viewModel.taskList[0].timeMin * 60).toInt()
        } else {
            20
        }
        setContent {
            val navController = rememberNavController()
            var progress by remember { mutableIntStateOf(0) }
            var timeText by remember { mutableStateOf(formatMillisToMMSS(timeSecond * 1000L)) }
            var currentPage by remember { mutableStateOf(HOME) }

            LaunchedEffect(Unit) {
                timer = PausableCountDownTimer(
                    timeSecond * 1000L, 1000,
                    onTick1 = { millisUntilFinished ->
                        progress =
                            ((timeSecond * 1000.0 - millisUntilFinished) / (timeSecond * 1000.0) * 100).toInt()
                        timeText = formatMillisToMMSS(millisUntilFinished)
                    }, onFinish1 = {
                        progress = 100
                        viewModel.taskList.removeAt(0)
                        if (viewModel.taskList.isEmpty()) {
                            viewModel.taskList.add(Task(System.currentTimeMillis(), "", 20L, false))
                        }
                        saveToMMKV()
                    })
            }
            val sweepAngle by animateIntAsState(
                targetValue = progress,
                animationSpec = tween(
                    easing = LinearEasing
                ),
                label = "sweepAngle"
            )

            PomodoroTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Column {
                        TitleView("首页")
                        NavHost(
                            modifier = Modifier.weight(1f),
                            navController = navController,
                            startDestination = HOME,
                        ) {
                            composable(HOME) {
                                CountDownView(sweepAngle, timeText)
                            }
                            composable(FIND) {
                            }
                            composable(ME) {
                            }
                        }


                        Row {
                            TabItem(
                                icon = if (currentPage == HOME) {
                                    R.drawable.ic_home_selected
                                } else {
                                    R.drawable.ic_home_unselected
                                },
                                HOME,
                                modifier = Modifier
                                    .weight(1f)
                                    .clickable {
                                        currentPage = HOME
                                        navController.navigate(HOME)
                                    })
                            TabItem(
                                icon = if (currentPage == FIND) {
                                    R.drawable.ic_find_selected
                                } else {
                                    R.drawable.ic_find_unselected
                                },
                                FIND,
                                modifier = Modifier
                                    .weight(1f)
                                    .clickable {
                                        currentPage = FIND
                                        navController.navigate(FIND)
                                    })
                            TabItem(
                                icon = if (currentPage == ME) {
                                    R.drawable.ic_me_selected
                                } else {
                                    R.drawable.ic_me_unselected
                                },
                                ME,
                                modifier = Modifier
                                    .weight(1f)
                                    .clickable {
                                        currentPage = ME
                                        navController.navigate(ME)
                                    })
                        }
                    }

                }
            }
        }
    }

    fun formatMillisToMMSS(millis: Long): String {
        val totalSeconds = millis / 1000
        val minutes = totalSeconds / 60
        val seconds = totalSeconds % 60
        return String.format("%02d:%02d", minutes, seconds)
    }

    @Composable
    fun TitleView(title: String) {
        Row(
            modifier = Modifier
                .height(80.dp)
                .statusBarsPadding()
                .fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                painterResource(R.mipmap.ic_back_arrow),
                "返回按钮",
                modifier = Modifier.width(50.dp)
            )
            Text(
                title,
                modifier = Modifier.weight(1f),
                fontWeight = FontWeight.Bold,
                fontStyle = FontStyle.Normal,
                textAlign = TextAlign.Center,
                fontSize = 16.sp
            )
            Icon(
                painterResource(R.drawable.add),
                "添加",
                modifier = Modifier
                    .width(50.dp)
                    .padding(horizontal = 15.dp, vertical = 8.dp)
                    .clickable {
                        launcher.launch(Intent(this@MainActivity, TaskListActivity::class.java))
                    }
            )
        }
    }

    @Composable
    fun TabItem(@DrawableRes icon: Int, text: String, modifier: Modifier) {
        Column(
            modifier = modifier.navigationBarsPadding(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(Modifier.height(12.dp).fillMaxWidth())
            Image(
                painter = painterResource(icon),
                "",
                Modifier.size(20.dp),
            )
            Spacer(Modifier.height(2.dp).fillMaxWidth())
            Text(text, style = TextStyle(fontSize = 12.sp))

        }
    }

    @Composable
    fun CountDownView(progress: Int, timeTextVal: String) {

        var playBtnText by remember { mutableStateOf("Start") }
        val sweepAngel = progress / 100f * 360f
        val width = 250
        if (progress == 100) {
            playBtnText = "Start"
            timer.cancel()
        }
        ConstraintLayout(
            modifier = Modifier
                .background(Color.Gray)
                .fillMaxSize()
        ) {
            val (baseCircle, topCircle, timeText, buttonsRow, descriptionBox) = createRefs()

            Canvas(
                modifier = Modifier
                    .width(width.dp)
                    .height(width.dp)
                    .constrainAs(baseCircle) {
                        top.linkTo(parent.top, margin = 80.dp)
                        start.linkTo(parent.start)
                        end.linkTo(parent.end)
                    }) {
                drawCircle(
                    color = Color.Blue,
                    width * density / 2f,

                    style = Stroke(width = 50f),
                )
            }
            Canvas(
                modifier = Modifier
                    .size(width.dp)
                    .constrainAs(topCircle) {
                        top.linkTo(baseCircle.top)
                        start.linkTo(baseCircle.start)
                        end.linkTo(baseCircle.end)
                    }
            ) {
                drawArc(
                    color = Color.Red,
                    startAngle = -90f,
                    sweepAngle = sweepAngel,
                    useCenter = false,
                    style = Stroke(width = 40f, cap = StrokeCap.Round),
                )
            }
            Text(
                timeTextVal,
                modifier = Modifier.constrainAs(timeText) {
                    top.linkTo(baseCircle.top)
                    start.linkTo(baseCircle.start)
                    end.linkTo(baseCircle.end)
                    bottom.linkTo(baseCircle.bottom)
                },
                fontSize = 30.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White
            )

            Box(
                Modifier
                    .fillMaxWidth()
                    .constrainAs(descriptionBox) {
                        top.linkTo(baseCircle.bottom, margin = 50.dp)
                        start.linkTo(baseCircle.start)
                        end.linkTo(baseCircle.end)
                    }
                    .padding(horizontal = 20.dp)
            ) {
                Text(
                    text = viewModel.taskList[0].description,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .background(Color.White, shape = RoundedCornerShape(8.dp))
                        .fillMaxWidth()
                        .align(Alignment.Center)
                        .padding(10.dp)
                )
            }

            Row(modifier = Modifier.constrainAs(buttonsRow) {
                top.linkTo(descriptionBox.bottom, margin = 80.dp)
                start.linkTo(descriptionBox.start)
                end.linkTo(descriptionBox.end)
            }) {
                Button(
                    onClick = {
                        if (viewModel.taskList.isEmpty()) return@Button
                        if (timer.isPaused) {
                            viewModel.taskList[0].running = true
                            saveToMMKV()
                            playBtnText = "Pause"
                            timer.resume()

                        } else {
                            playBtnText = "Continue"
                            timer.pause()
                        }
                    },
                ) { Text(playBtnText) }
                Box(modifier = Modifier.width(50.dp))
                Button(
                    onClick = {
                        if (viewModel.taskList.isEmpty()) return@Button
                        playBtnText = "Start"
                        timer.cancel()
                    },
                ) { Text("Stop") }
            }
        }

    }

    @Composable
    fun Reset() {
        timer.cancel()


    }

    private fun loadJobs(): MutableList<Task> {
        val jobsCacheString = MMKV.defaultMMKV().decodeString(KEY_JOBS)
        val type = object : TypeToken<MutableList<Task>>() {}.type
        return Gson().fromJson<MutableList<Task>?>(jobsCacheString, type).takeIf { it != null }
            ?: mutableListOf()
    }

    private fun saveToMMKV() {
        MMKV.defaultMMKV().encode(KEY_JOBS, Gson().toJson(viewModel.taskList))
    }
}
